//
// Created by Administrator on 2022/10/21.
//

//使用链式存储实现栈,使用链表的头节点作为栈顶节点

#include <stdio.h>
#include <malloc.h>

#define ERROR 0
#define OK 1
typedef int ElementType;
typedef int Status;
//声明链栈节点
typedef struct LinkStackNode{
    ElementType data;
    struct LinkStackNode* next;
}LinkStackNode,*LinkStackPtr;
//声明链栈
typedef struct {
    LinkStackPtr top;
    int count;
}LinkStack;

//初始化一个链栈
void initLinkStack(LinkStack* linkStack){
    (*linkStack).top=NULL;
    (*linkStack).count=0;
}
//向栈中压入一个元素
Status push(LinkStack* stack,ElementType e){
    LinkStackPtr p=(LinkStackPtr)malloc(sizeof(struct LinkStackNode));
    p->data = e;
    p->next = stack->top;
    stack->top = p;
    stack->count++;
    return OK;
}
//出栈一个元素
Status pop(LinkStack* stack,ElementType* e){
    if(stack->count==0){
        return ERROR; //栈为空
    }
    *e = stack->top->data;
    LinkStackPtr p =stack->top;
    stack->top=p->next;
    free(p);
    stack->count--;
    return OK;
}
//显示栈中的所有元素
void showLinkStack(LinkStack stack){
    LinkStackPtr p =stack.top;
    while(p){
        printf("%d\n",p->data);
        p=p->next;
    }
}

void main(){
    LinkStack stack;
    initLinkStack(&stack);
    printf("压栈:");
    push(&stack,0);
    push(&stack,1);
    push(&stack,2);
    push(&stack,3);
    push(&stack,4);
    showLinkStack(stack);
    printf("开始出栈:\n");
    int tmp;
    pop(&stack,&tmp);
    printf("%d\n", tmp);
    pop(&stack,&tmp);
    printf("%d\n", tmp);
    pop(&stack,&tmp);
    printf("%d\n", tmp);
    pop(&stack,&tmp);
    printf("%d\n", tmp);
    printf("剩余元素为:\n");
    showLinkStack(stack);
}
